package com.tanhua.server.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.SoundApi;
import com.tanhua.dubbo.server.pojo.Sound;
import com.tanhua.dubbo.server.vo.SoundVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
/**
 * Create By Administrator on 2021/7/11.
 */
@Service
@Slf4j
public class SoundService {

    @Reference(version = "1.0.0")
    private SoundApi soundApi;

    @Autowired
    protected FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private UserInfoService userInfoService;



    public Boolean saveSound(MultipartFile soundFile) {

        Sound sound = new Sound();
        // 设置上传音频着的用户id
        sound.setUserId(UserThreadLocal.get().getId());

        try {

            StorePath storePath = this.storageClient.uploadFile(soundFile.getInputStream(),
                    soundFile.getSize(),
                    StrUtil.subAfter(soundFile.getOriginalFilename(), '.', true),
                    null);
            sound.setSoundUrl(fdfsWebServer.getWebServerUrl() + storePath.getFullPath());
            String s = soundApi.saveSound(sound);
            return StrUtil.isNotEmpty(s);

        } catch (IOException e) {
            log.error("桃花传音出错~  = ", e);
        }
        return null;
    }

    public SoundVo getSound() {

        SoundVo soundVo = new SoundVo();

        Sound sound = this.soundApi.receptionsound();

        soundVo.setUId(sound.getUserId());//设置音频来源者的id

        soundVo.setSoundUrl(sound.getSoundUrl());//设置音频地址

        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(sound.getUserId());

        soundVo.setAvatar(userInfo.getLogo());//设置头像

        soundVo.setNickname(userInfo.getNickName());//设置昵称

        soundVo.setGender(userInfo.getSex().toString());//设置性别

        Integer count = soundApi.querySoudById(sound.getUserId()); // 根据id 获得用户今日接受传音的次数

        if(count<=0){
            return null;
        }

        soundVo.setRemainingTimes(count); //设置次数

        return soundVo;
    }
}
